package com.zj.osm.view.home.home.home_fragment.twofragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.zj.osm.R;
import com.zj.osm.bean.Filter;
import com.zj.osm.bean.LocalSelectedEnum;
import com.zj.osm.mvp.MvpFragment;
import com.zj.osm.view.home.home.home_fragment.twofragment.page.LocalProjectFragment;
import com.zj.osm.view.home.home.home_fragment.twofragment.page.OnButtonVisibleListenner;
import com.zj.osm.view.project.addproject.AddProjectActivity;
import com.zj.utils.utils.Utils;
import com.zj.utils.utils.filter.FiltrateBean;
import com.zj.utils.utils.filter.FlowPopWindow;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import static com.zj.osm.view.home.home.home_fragment.onefragment.OneFragment.DIALOG_BOTTOM;

public class TwoFragment extends MvpFragment<TwoFragmentView, TwoFragmentPresenter> implements View.OnClickListener, TwoFragmentView, OnButtonVisibleListenner {
    private final List<View> views = new ArrayList<>();
    private ViewPager two_viewPager;
    private EditText two_editText;
    private TextView two_local;
    private TextView two_online;
    private boolean isOneClick = true;//是否第一次点击排序
    private LocalProjectFragment localProjectFragment1;
    private LocalProjectFragment localProjectFragment2;
    private FlowPopWindow flowPopWindow;

    private List<FiltrateBean> dictList = new ArrayList<>();
    private TextView two_shaixuan;
    private TextView shaixuanTv;
    private LinearLayout three_shaixuan;
    private TextView activity_tv_save;
    private ImageView addProjectIv;
    private ImageButton two_ib_search;


    @Override
    public TwoFragmentPresenter createPresenter() {
        return new TwoFragmentPresenter();
    }

    @Override
    public TwoFragmentView createView() {
        return this;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.two_fragment_lt;

    }

    @Override
    protected void initView(@NotNull View view) {
        super.initView(view);
        two_viewPager = view.findViewById(R.id.two_viewPager);
        //two_viewPager.setOnClickListener(this);
        two_editText = view.findViewById(R.id.two_editText);
        two_online = view.findViewById(R.id.two_online);
        two_local = view.findViewById(R.id.two_local);
        two_shaixuan = view.findViewById(R.id.two_shijian);
        three_shaixuan = view.findViewById(R.id.two_shaixuan);
        activity_tv_save = view.findViewById(R.id.activity_tv_save);
        activity_tv_save.setOnClickListener(this);
        addProjectIv = view.findViewById(R.id.activity_iv_add);
        addProjectIv.setOnClickListener(this);
        two_ib_search = view.findViewById(R.id.two_ib_search);

        TextView two_zonghe = view.findViewById(R.id.two_zonghe);
        two_zonghe.setOnClickListener(this);
        localProjectFragment1 = new LocalProjectFragment(getActivity());
        localProjectFragment1.init(this);
        localProjectFragment2 = new LocalProjectFragment(getActivity());
        localProjectFragment1.init(this);
        views.add(localProjectFragment1);
        views.add(localProjectFragment2);
        setViewPager();
        initParam();
    }

    @Override
    public void initListener() {
        two_online.setOnClickListener(this);
        two_local.setOnClickListener(this);
        two_shaixuan.setOnClickListener(this);
        three_shaixuan.setOnClickListener(this);
        two_ib_search.setOnClickListener(this);

        /*
        点击搜索框时软键盘变成搜索按钮，点击搜索后自动隐藏软键盘
         */
        two_editText.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        two_editText.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                toSearch(two_editText.getText().toString().trim(), getActivity());
                return true;
            }
            return false;
        });

        /*
        监听搜索框内容，为空时自动显示全部项目
         */
        two_editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (0 == s.length()) {
                    localProjectFragment1.getProjectList();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void hideKeyboard(View view) {
        InputMethodManager manager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.two_zonghe:
                orderAsc();
                break;
            case R.id.two_shijian:
                orderAsc();
                break;
            case R.id.two_shaixuan:
                showShaixuan();
                break;
            //本地项目
            case R.id.two_local:
                try {
                    two_viewPager.setCurrentItem(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                two_editText.setText("");
                two_local.setTextColor(Color.rgb(255, 255, 255));
                two_online.setTextColor(Color.rgb(51, 51, 51));
                two_local.setBackgroundResource(R.drawable.btn_city);
                two_online.setBackgroundResource(R.drawable.btn_down_white);
                break;
            //在线项目
            case R.id.two_online:
                two_viewPager.setCurrentItem(1);
                two_editText.setText("");
                two_online.setTextColor(Color.rgb(255, 255, 255));
                two_local.setTextColor(Color.rgb(51, 51, 51));
                two_local.setBackgroundResource(R.drawable.btn_city_white);
                two_online.setBackgroundResource(R.drawable.btn_down);
                break;
            //管理
            case R.id.activity_tv_save:
                if (DIALOG_BOTTOM) {
                    DIALOG_BOTTOM = false;
                    activity_tv_save.setText("关闭");
                    localProjectFragment1.setGuanliListItem(View.VISIBLE, false);

                } else {
                    DIALOG_BOTTOM = true;
                    localProjectFragment1.setGuanliListItem(View.GONE, true);
                    activity_tv_save.setText("管理");

                }
                break;
            case R.id.activity_iv_add:
                Intent intent = new Intent(getContext(), AddProjectActivity.class);
                startMyActivity(intent);
                break;
            case R.id.two_ib_search:
                toSearch(two_editText.getText().toString().trim(), getActivity());
                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        if (localProjectFragment1 != null) {
            localProjectFragment1.getOnResum();
        }
        super.onResume();
    }


    private void showShaixuan() {
        flowPopWindow = new FlowPopWindow(getActivity(), dictList);
        flowPopWindow.showAsDropDown(two_shaixuan);
        Log.e("showDorwp", "laine?");
        final List<Filter> filter = new ArrayList<>();
        filter.clear();
        flowPopWindow.setOnConfirmClickListener(() -> {
            for (FiltrateBean fb : dictList) {
                List<FiltrateBean.Children> cdList = fb.getChildren();
                for (int x = 0; x < cdList.size(); x++) {
                    FiltrateBean.Children children = cdList.get(x);
                    if (children.isSelected()) {
                        filter.add(new Filter(fb.getTypeName(), children.getValue()));
                    }
                }
            }
            if (filter.size() > 0) {
                for (int i = 0; i < filter.size(); i++) {
                    if ("获取方式".equals(filter.get(i).getName())) {
                        localProjectFragment1.setOtherOrder(LocalSelectedEnum.LOCAL_TYPE, filter.get(i));

                    }
                    if ("建设类型".equals(filter.get(i).getName())) {
                        localProjectFragment1.setOtherOrder(LocalSelectedEnum.PROJECT_STATE, filter.get(i));
                    }
                    if ("电压等级".equals(filter.get(i).getName())) {
                        localProjectFragment1.setOtherOrder(LocalSelectedEnum.VOLTAGE_LEVEL, filter.get(i));
                    }
                }
            }
        });

    }

    /**
     * 项目排序
     */
    private void orderAsc() {
        if (isOneClick) {
            localProjectFragment1.setAsc();
            isOneClick = !isOneClick;
        } else {
            localProjectFragment1.setDesc();
            isOneClick = !isOneClick;
        }
    }

    /**
     * 设置viewpager
     */
    private void setViewPager() {
        two_viewPager.setAdapter(new PagerAdapter() {
            @Override
            public int getCount() {
                return 1;
            }

            @Override
            public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
                return view == object;
            }

            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) {
                View view3 = views.get(position);
                container.addView(view3);
                return view3;
            }

            @Override
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
                container.removeView(views.get(position));
            }

        });
//        two_viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                if (position == 0) {
//                    two_editText.setText("");
//                    two_editText.setText("");
//                    two_local.setTextColor(Color.rgb(255, 255, 255));
//                    two_online.setTextColor(Color.rgb(51, 51, 51));
//                    two_local.setBackgroundResource(R.drawable.btn_city);
//                    two_online.setBackgroundResource(R.drawable.btn_down_white);
//                } else {
//                    two_editText.setText("");
//                    two_editText.setText("");
//                    two_online.setTextColor(Color.rgb(255, 255, 255));
//                    two_local.setTextColor(Color.rgb(51, 51, 51));
//                    two_local.setBackgroundResource(R.drawable.btn_city_white);
//                    two_online.setBackgroundResource(R.drawable.btn_down);
//                }
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });

    }

    /**
     * 添加筛选框的数据
     */
    private void initParam() {
        String[] sexs = {"本地", "在线"};
        String[] colors = {"新建", "原有", "改造"};
        String[] company = {"0.4kV", "10kV", "20kV"};
        //String[] times = {"最近三天", "最近一周", "最近一月"};
        FiltrateBean fb1 = new FiltrateBean();
        fb1.setTypeName("获取方式");
        List<FiltrateBean.Children> childrenList = new ArrayList<>();
        for (String sex : sexs) {
            FiltrateBean.Children cd = new FiltrateBean.Children();
            cd.setValue(sex);
            childrenList.add(cd);
        }
        fb1.setChildren(childrenList);

        FiltrateBean fb2 = new FiltrateBean();
        fb2.setTypeName("建设类型");
        List<FiltrateBean.Children> childrenList2 = new ArrayList<>();
        for (String color : colors) {
            FiltrateBean.Children cd = new FiltrateBean.Children();
            cd.setValue(color);
            childrenList2.add(cd);
        }
        fb2.setChildren(childrenList2);

        FiltrateBean fb3 = new FiltrateBean();
        fb3.setTypeName("电压等级");
        List<FiltrateBean.Children> childrenList3 = new ArrayList<>();
        for (String aCompany : company) {
            FiltrateBean.Children cd = new FiltrateBean.Children();
            cd.setValue(aCompany);
            childrenList3.add(cd);
        }
        fb3.setChildren(childrenList3);
        dictList.add(fb1);
        dictList.add(fb2);
        dictList.add(fb3);
        //dictList.add(fb4);
    }


    @Override
    public void onButtonVisibleListener() {
        activity_tv_save.setText("管理");
    }

    /**
     * 发起搜索
     *
     * @param searchContent 搜索内容（不为空）
     * @param activity 当前activity，隐藏软键盘时需要
     */
    private void toSearch(String searchContent, Activity activity){
        if (null == searchContent || "".equals(searchContent)) {
            Toast.makeText(getContext(), getString(R.string.non_null_search), Toast.LENGTH_SHORT).show();
        } else {
            localProjectFragment1.searchProjects(searchContent);
            Utils.INSTANCE.hideKeyboard(getActivity());
        }
    }
}
